<template xmlns="http://www.w3.org/1999/html">
  <div>
    <el-popover ref="popoverRef" :offset="0" :placement="placement" :visible="visibleOpen" :width="width"
                trigger="click">

      <template #reference>
        <el-input ref="inputRef" v-model="itemName" placeholder="请输入需要检索的数据" @blur="itemNameBlur"
                  @focus="itemNameFocus" @input="itemNameInput" @keydown="onKeyDown"/>
      </template>
      <div v-click-outside="visibleOpenFalse">
        <el-row :gutter="10">
          <el-col :span="leftSpan">
            <el-table ref="tabRef" :border="true" :data="tableBodyList" height="260px" highlight-current-row stripe
                      @row-dblclick="rowDblclick" @row-click="handleRowClick" @current-change="handleCurrentChange">
              <el-table-column v-for="(item, index) in tableHeadList" :key="index"
                               :align="item.align ? item.align : 'center'" :label="item.label" :property="item.prop"
                               :show-overflow-tooltip="true" :width="item.width ? item.width : '90'">
                <template #default="scope">
                        <span v-if="item.class === 'dict'">
                            <dict-data-tag :options="dictDataMap[item.dictType]" :value="scope.row[item.prop]"/>
                        </span>
                  <span v-else-if="item.class === 'date'">
                            <span>{{ $parseTime(scope.row[item.prop], "{y}-{m}-{d}") }}</span>
                        </span>
                  <span v-else-if="item.class === 'time'">
                            <span>{{
                                $parseTime(scope.row[item.prop], "{y}-{m}-{d} {h}:{i}:{s}")
                              }}</span>
                        </span>
                  <span v-else>
                            <span :style="{ color: (item.color ? item.color : '#606266') }">{{
                                scope.row[item.prop]
                              }}</span>
                        </span>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
          <el-col :span="rightSpan">
            <div style="height: 260px; min-width: 280px ;  overflow-y: auto;">
              <el-empty v-if="Object.keys(selectRow).length === 0" :image-size="60" description="暂无数据"></el-empty>
              <div
                v-else-if="selectRow && (rightDivShowType === 'westernMedicine' || rightDivShowType === 'westernMedicineByTemplate')">
                <div><span class="right-div-span">药品分类：</span>{{ selectRow.drugClassName }}<span
                  class="right-div-span ml20">药品类别：</span>{{ selectRow.drugTypeName }}
                </div>
                <div>
                  <span class="right-div-span">包装数量：</span>{{ selectRow.packageNum }}
                  <span v-if="rightDivShowType === 'westernMedicine'" class="right-div-span  ml20"
                        style=" color: rgb(255, 0, 0);">已占用库存：{{ selectRow.reductionAmountShow }}</span>
                </div>
                <div><span class="right-div-span">是否抗菌药物：</span>{{
                    selectRow.antisepticType === 'Y' ? '是' : '否'
                  }}
                </div>
                <div v-if="rightDivShowType === 'westernMedicine'"><span class="right-div-span">有效期(距离最近)：</span>
                  <span class="right-div-span"
                        style=" color: rgb(255, 0, 0);">{{
                      $parseTime(selectRow.expireDate, '{y}-{m}-{d}')
                    }}</span></div>
                <div><span class="right-div-span">毒麻分类：</span>{{ selectRow.toxiPropertyName }}</div>
                <div><span class="right-div-span">限制等级：</span>{{ selectRow.limitClassName }}</div>
                <div><span class="right-div-span">是否医保：</span>{{ selectRow.zfOrYb === '1' ? '医保' : '自费' }}</div>
                <div><span class="right-div-span">医保项目编码：</span>{{ selectRow.countryYbCode }}</div>
                <div><span class="right-div-span">医保项目名称：</span>{{ selectRow.countryYbName }}</div>
                <div><span class="right-div-span">厂家：</span>{{ selectRow.firmName }}</div>
                <div><span class="right-div-span">大小包装：</span>{{ selectRow.packageSizeInfo }}</div>
              </div>
              <div v-else-if="selectRow && rightDivShowType === 'drugImportAndExport'">
                <div><span class="right-div-span">药品分类：</span>{{ selectRow.drugClassName }}<span
                  class="right-div-span ml20">药品类别：</span>{{ selectRow.drugTypeName }}
                </div>
                <div><span class="right-div-span">毒麻分类：</span>{{ selectRow.toxiPropertyName }}</div>
                <div><span class="right-div-span">是否抗菌药物：</span>{{
                    selectRow.antisepticType === 'Y' ? '是' : '否'
                  }}
                </div>
                <div><span class="right-div-span">限制等级：</span>{{ selectRow.limitClassName }}</div>
                <div><span class="right-div-span">是否医保：</span>{{ selectRow.zfOrYb === '1' ? '医保' : '自费' }}</div>
                <div><span class="right-div-span">医保项目编码：</span>{{ selectRow.countryYbCode }}</div>
                <div><span class="right-div-span">医保项目名称：</span>{{ selectRow.countryYbName }}</div>
                <div><span class="right-div-span">厂家：</span>{{ selectRow.firmName }}</div>
                <div><span class="right-div-span">大小包装：</span>{{ selectRow.packageSizeInfo }}</div>
                <div><span class="right-div-span">包装数量：</span>{{ selectRow.packageNum }}</div>
              </div>
            </div>
          </el-col>
          <span style="color: #0b9aff; ">鼠标左键双击需要选择的项目<el-button style="position: absolute; right: 5px;"
                                                                              @click="closePopover">
            关闭
          </el-button></span>

        </el-row>
      </div>
    </el-popover>
  </div>
</template>

<script lang="ts" setup>
import {useDictStoreHook} from "@/store/modules/dict";
import {onBeforeUnmount} from "vue";

const {proxy} = getCurrentInstance() as any;
const dictStore = useDictStoreHook();
const emits = defineEmits(["closePopover", "rowClick", "itemNameInput"]);
const popoverRef = ref();
const itemName = ref();
const inputRef = ref();
//自动补全表格
const tabRef = ref();
let dictTypeArray = ref<any>([]);
const props = defineProps({
  // 窗体名称
  title: {
    type: String,
    default: "自动补全",
  },
  // 窗体弹出位置
  placement: {
    type: String,
    default: "bottom",
  },
  // 窗体宽度
  width: {
    type: Number,
    default: 877,
  },
  // 自动补全表格表头
  tableHeadList: {
    type: Array,
    default: [],
  },
  // 自动补全表格数据
  tableBodyList: {
    type: Array,
    default: [],
  },
  dictArray: {
    type: Array,
    default: [],
  },
  // 右侧项目信息显示类型
  rightDivShowType: {
    type: String,
    default: "",
  },
  leftSpan: {
    type: Number,
    default: 17
  },
  rightSpan: {
    type: Number,
    default: 7
  }
});
// 选中的行数据
const selectRow = ref<any>({})
//@ts-ignore
const dictDataMap = ref(dictStore.isTypeGetDataArrays(props.dictArray));
dictTypeArray.value = props.dictArray;
// 是否显示窗体
const visibleOpen = ref(false);
// 当前选中的行索引
const currentRowIndex = ref(-1);

onBeforeUnmount(() => {
  itemNameEmpty();
});


/** 初始化窗体、打开自动补全窗体 */
function init() {
  visibleOpen.value = true;
}

function setItemName(itemNameStr) {
  itemName.value = itemNameStr;
}


/**
 * 动态行中固定input框获取焦点事件
 */
const focusInput = () => {
  inputRef.value.focus();
};

/** 行点击事件 */
function handleRowClick(row) {
  if (row.reductionAmount % row.packageNum === 0) {
    // 是否能够整除
    row.reductionAmountShow = row.reductionAmount / row.packageNum + row.packageUnitsName
  } else {
    row.reductionAmountShow = Math.floor(row.reductionAmount / row.packageNum) + row.packageUnitsName
      + row.reductionAmount % row.packageNum + row.minUnitsName
  }
  selectRow.value = row;
}

/** 行双击事件 */
function rowDblclick(row) {
  itemName.value = row.itemName;
  selectRow.value = row;
  emits("rowClick", row);
}

/**
 * 点击table外部元素关闭自动补全窗口
 */
function visibleOpenFalse() {
  closePopover()
}

/** 关闭自动补全窗口 */
function closePopover() {
  visibleOpen.value = false;
  currentRowIndex.value = -1;
}

/** 项目名称获取焦点事件 */
function itemNameFocus() {
  if (visibleOpen.value) {
    emits("itemNameInput", itemName.value);
  }
}

/** 项目名称失去焦点事件 */
function itemNameBlur() {
}

/** 项目名称自动补全检索 */
function itemNameInput(value) {
  emits("itemNameInput", value);
}

function itemNameEmpty() {
  itemName.value = "";
  closePopover();
}

const blurInput = () => {
  inputRef.value.blur();


};

// 处理键盘事件
function onKeyDown(event: KeyboardEvent) {

  console.log(currentRowIndex.value);
  if (event.key === 'ArrowDown') {
    event.preventDefault();
    if (currentRowIndex.value < props.tableBodyList.length - 1) {
      currentRowIndex.value++;
    }
    console.log(tabRef)
    tabRef.value.setCurrentRow(props.tableBodyList[currentRowIndex.value])
    selectRow.value = props.tableBodyList[currentRowIndex.value]
  } else if (event.key === 'ArrowUp') {
    event.preventDefault();
    if (currentRowIndex.value > 0) {
      currentRowIndex.value--;
    }
    tabRef.value.setCurrentRow(props.tableBodyList[currentRowIndex.value])
    selectRow.value = props.tableBodyList[currentRowIndex.value]
  } else if (event.key === 'Enter') {
    event.preventDefault();
    if (currentRowIndex.value !== -1) {
      rowDblclick(props.tableBodyList[currentRowIndex.value]);
    }
  }

}

//当前选中数据
const currentRow = ref(null);

//选中行事件
function handleCurrentChange(val) {
  currentRow.value = val;
  // if (currentRow.value) {
  //   scrollToCurrentRow();
  // }
}

//设置滚动条
function scrollToCurrentRow() {
  if (!currentRow.value || !tabRef.value) return;
  // 获取当前行的 DOM 元素
  const rowElement = (tabRef.value as any).$el.querySelector(`.el-table__row.current-row`);
  if (rowElement) {
    // 使用 scrollIntoView 将当前行滚动到可见区域
    rowElement.scrollIntoView({block: 'center'});
  }
}

defineExpose({
  closePopover,
  init,
  itemNameEmpty,
  setItemName,
  focusInput,
  itemNameFocus
});
</script>
<script lang="ts">
export default {
  // 自动补全
  name: "AutomaticCompletionIndex",
};
</script>

<style scoped>
.right-div-span {
  font-weight: bold;
  color: #000000;
}
</style>
